/*
 * sound.cpp
 *
 *  Created on: 22/12/2008
 *      Author: smaxll
 */

#include "sound.hpp"

#include <cstdlib>
#include <iostream>
#include <SDL/SDL.h>
#include <SDL/SDL_mixer.h>

namespace {

int music_start_time = 0;
bool want_new_music = false;
int fadingout_time=5000;
bool no_fading = false;
const int numChannels = 2;

struct music_track
{
    music_track(const std::string tname);
    music_track(const std::string &tname,
                const std::string &ms_before_str,
                const std::string &ms_after_str);
//    void write(config &snapshot, bool append);

    std::string name;
    unsigned int ms_before, ms_after;
    bool once;
};

music_track::music_track(const std::string tname)
    : name(tname), ms_before(0), ms_after(0), once(false)
{
}

std::vector<music_track> current_track_list;
struct music_track current_track("");
struct music_track last_track("");

}


namespace sound {
    /**
     * Initialize the sound system
     * This function should be called first before any SDL_mixer function is called
     */
    bool init() {
        if(SDL_Init(SDL_INIT_AUDIO) < 0) {
            std::cout << "SDL_Init error: " << SDL_GetError() << std::endl;
            exit(EXIT_FAILURE);
        }

        if (Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 4096) == -1) {
            std::cout << "Error en Mix_OpenAudio: "<< Mix_GetError() << std::endl;
            exit(EXIT_FAILURE);
        }

    }

    bool close() {
        Mix_CloseAudio();
    }

    bool close_music(Mix_Music* music){
        Mix_FreeMusic(music);
    }

    void play_music_repeatedly(const std::string musicName){
        if(musicName.empty()){
            return;
        }

        current_track_list = std::vector<music_track>(1, music_track(musicName));

        // If we're already playing it, don't interrupt.
        if (current_track.name != musicName) {
            current_track = music_track(musicName);
            play_music();
        }

    }

    void play_music() {
        music_start_time = 1; //immediate (same as effect as SDL_GetTicks())
        want_new_music=true;
        no_fading=false;
        fadingout_time=current_track.ms_after;

        Mix_Music *music;
        std::string musicName = "sounds/"+current_track.name;
        music = Mix_LoadMUS(musicName.c_str());

        if (!music){
            std::cerr << "Error en Mix_LoadMUS: \n" << Mix_GetError() << std::endl;
        } else {
            Mix_PlayMusic(music, 0);
        }

    }


}
